package component
{
	import com.bit101.components.HBox;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	import view.CanvasFrame;
	
	public class Image extends Sprite
	{
		[Embed(source="assets/swf/loading.swf")]
		private var cls:Class;
		public var loading:MovieClip;
		private var loader:Loader = new Loader();
		public var data:Object;
		public var bitmap:Bitmap;
		public var maxH:int = 154;
		public var maxW:int = 154;
		private var time:uint;
		private var txt:TextField;
		public function Image(drawAble:Boolean=true)
		{
			super();
			loading = new cls();
			if(drawAble)
				drawTihs();
		}
		public function drawTihs():void{
			this.graphics.beginFill(0x666666,0.5)
			this.graphics.drawRect(0,0,maxH,maxH);
			this.graphics.endFill();
		}
		public function setSource(url:String):void{
			loader.unload();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioError);
			loader.load(new URLRequest(url));
			this.addChild(loading);
			loading.x = (maxH - loading.height) * 0.5;
			loading.y = (maxW - loading.width) * 0.5;
			this.addEventListener(MouseEvent.CLICK,onMouseClick);
		}
		public function onComplete(event:Event):void{
			bitmap = event.target.content;
			this.removeChild(loading);
			this.addChild(bitmap);
			if(bitmap.height < maxH){
				bitmap.y = (maxH - bitmap.height) * 0.5;
			}else{
				var sc:Number = maxH/bitmap.height;
				bitmap.scaleX = bitmap.scaleY = sc;
			}
			this.graphics.clear();
			HBox(this.parent).onResize();
		}
		public function onMouseClick(event:Event):void{
			CanvasFrame.getInstance().runClick(this.x + this.width,data,bitmap);
		}
		private function ioError(event:IOErrorEvent):void{
			trace("ioerror");
		}
		public function addTxt(str:String):void{
			txt = new TextField();
			txt.width = maxW;
			txt.height = 25;
			txt.y = maxH + 10;
			txt.textColor = 0xaa503c;
			this.addChild(txt);
			txt.selectable = false;
			txt.text = str;
		}
		
		
		
	}
}